<template>
  <div class="factory-page">
    <!-- 页面标题与返回按钮 -->
    <div class="page-header">
      <h2 class="page-title">我的工厂列表</h2>
      <el-button type="text" class="return-btn" @click="handleReturn">返回</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input 
        v-model="searchKey" 
        placeholder="请输入搜索内容" 
        style="width: 200px;" 
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" class="search-btn" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 工厂列表表格 -->
    <el-table 
      :data="filteredFactoryList" 
      border 
      stripe 
      style="width: 100%; margin-top: 15px;"
      size="small"
    >
      <el-table-column prop="brand" label="品牌" sortable align="center" />
      <el-table-column prop="agentBrand" label="代理品牌" sortable align="center" />
      <el-table-column prop="address" label="地址" sortable align="center" />
      <el-table-column prop="responsiblePerson" label="负责人" sortable align="center" />
      <el-table-column prop="contact" label="联系方式" sortable align="center" />
      <el-table-column prop="brandDiscount" label="品牌折扣" sortable align="center" />
      <el-table-column prop="brandManager" label="品牌经理" sortable align="center" />
      <el-table-column prop="instructor" label="导师" sortable align="center" />
      <el-table-column prop="cashAccount" label="现金账户" sortable align="center" />
      <el-table-column prop="retailFundAccount" label="零售价资金账户" sortable align="center" />
      <el-table-column prop="retailDeliveryAccount" label="零售配送货账户" sortable align="center" />
      <el-table-column prop="email" label="邮箱" sortable align="center" />
      <el-table-column label="采购订单" align="center">
        <template #default>
          <el-button type="primary" size="mini" @click="handleAddPurchase">新增采购</el-button>
          <el-button type="default" size="mini" @click="handleHistoryOrder" style="margin-left: 5px;">往期订单</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default>
          <el-button type="success" size="mini" @click="handleView">查看</el-button>
          <el-button type="info" size="mini" @click="handleMaterialLibrary" style="margin-left: 5px;">素材库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area" style="margin-top: 15px; display: flex; align-items: center; gap: 10px;">
      <span>共 {{ total }} 条 共 {{ totalPages }} 页</span>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total"
      />
      <el-select 
        v-model="pageSize" 
        @change="handleSizeChange" 
        placeholder="条数/页" 
        style="width: 100px;"
        size="small"
      >
        <el-option label="10条/页" value="10" />
        <el-option label="20条/页" value="20" />
        <el-option label="30条/页" value="30" />
      </el-select>
      <span>跳至</span>
      <el-input 
        v-model="jumpPage" 
        type="number" 
        style="width: 50px; margin: 0 5px;"
        size="small"
        @keyup.enter="handleJumpPage"
      />页
      <el-button type="primary" size="small" @click="handleJumpPage">确定</el-button>
    </div>

    <!-- 新增采购弹窗 -->
    <el-dialog title="新增采购" v-model="addPurchaseVisible" width="60%" top="10vh">
      <el-form :model="purchaseForm" label-width="120px" size="default">
        <el-form-item label="采购工厂">
          <el-input v-model="purchaseForm.factory" disabled />
        </el-form-item>
        <el-form-item label="采购商品" prop="product">
          <el-input v-model="purchaseForm.product" placeholder="请输入采购商品" />
        </el-form-item>
        <el-form-item label="采购数量" prop="count">
          <el-input v-model.number="purchaseForm.count" placeholder="请输入采购数量" type="number" min="1" />
        </el-form-item>
        <el-form-item label="采购金额" prop="amount">
          <el-input v-model="purchaseForm.amount" placeholder="请输入采购金额" prefix-icon="el-icon-money" />
        </el-form-item>
        <el-form-item label="采购备注">
          <el-input v-model="purchaseForm.remark" type="textarea" rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addPurchaseVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePurchase">确定</el-button>
      </template>
    </el-dialog>

    <!-- 往期订单弹窗 -->
    <el-dialog title="往期订单" v-model="historyOrderVisible" width="70%" top="10vh">
      <el-table :data="historyOrderList" border stripe size="small">
        <el-table-column prop="orderNo" label="订单编号" align="center" />
        <el-table-column prop="product" label="采购商品" align="center" />
        <el-table-column prop="count" label="采购数量" align="center" />
        <el-table-column prop="amount" label="采购金额" align="center" />
        <el-table-column prop="createTime" label="采购时间" align="center" />
        <el-table-column prop="status" label="订单状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="historyOrderVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 工厂详情弹窗 -->
    <el-dialog title="工厂详情" v-model="factoryDetailVisible" width="70%" top="10vh">
      <el-descriptions column="2" border>
        <el-descriptions-item label="品牌">{{ currentFactory.brand }}</el-descriptions-item>
        <el-descriptions-item label="代理品牌">{{ currentFactory.agentBrand }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ currentFactory.address }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ currentFactory.responsiblePerson }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentFactory.contact }}</el-descriptions-item>
        <el-descriptions-item label="品牌经理">{{ currentFactory.brandManager }}</el-descriptions-item>
        <el-descriptions-item label="导师">{{ currentFactory.instructor }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentFactory.email }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="factoryDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 素材库弹窗 -->
    <el-dialog title="素材库" v-model="materialLibraryVisible" width="70%" top="10vh">
      <el-upload
        class="upload-demo"
        action="#"
        list-type="picture-card"
        :file-list="materialFileList"
        :on-preview="handlePreview"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog v-model="previewVisible" title="素材预览" width="80%">
        <img :src="previewUrl" style="width: 100%;" />
      </el-dialog>
      <template #footer>
        <el-button @click="materialLibraryVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, toRefs } from 'vue';
import { ElMessage } from 'element-plus';

// 状态管理
const state = reactive({
  searchKey: '',
  factoryList: [],
  filteredFactoryList: [],
  currentPage: 1,
  pageSize: 10,
  jumpPage: '',
  total: 0,
  addPurchaseVisible: false,
  historyOrderVisible: false,
  factoryDetailVisible: false,
  materialLibraryVisible: false,
  previewVisible: false,
  previewUrl: '',
  currentFactory: {},
  purchaseForm: {
    factory: '',
    product: '',
    count: 1,
    amount: '',
    remark: ''
  },
  historyOrderList: [],
  materialFileList: [
    {
      name: '工厂宣传图1.png',
      url: 'https://example.com/image1.png'
    },
    {
      name: '产品手册.pdf',
      url: 'https://example.com/manual.pdf'
    }
  ]
});

const {
  searchKey,
  factoryList,
  filteredFactoryList,
  currentPage,
  pageSize,
  jumpPage,
  total,
  addPurchaseVisible,
  historyOrderVisible,
  factoryDetailVisible,
  materialLibraryVisible,
  previewVisible,
  previewUrl,
  currentFactory,
  purchaseForm,
  historyOrderList,
  materialFileList
} = toRefs(state);

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value) || 1;
});

// 初始化工厂数据
const initFactoryData = () => {
  factoryList.value = [
    {
      brand: '工厂A',
      agentBrand: '阿玛尼',
      address: '江苏省南京市建邺区',
      responsiblePerson: '李云',
      contact: '15156107482',
      brandDiscount: '',
      brandManager: '张虎',
      instructor: '李笑笑',
      cashAccount: '',
      retailFundAccount: '',
      retailDeliveryAccount: '',
      email: '248439182@qq.com'
    },
    {
      brand: '工厂A',
      agentBrand: '阿玛尼',
      address: '江苏省南京市建邺区',
      responsiblePerson: '李云',
      contact: '15156107482',
      brandDiscount: '',
      brandManager: '张虎',
      instructor: '李笑笑',
      cashAccount: '',
      retailFundAccount: '',
      retailDeliveryAccount: '',
      email: '248439182@qq.com'
    }
  ];
  filteredFactoryList.value = [...factoryList.value];
  total.value = filteredFactoryList.value.length;
};

// 初始化数据
initFactoryData();

// 搜索功能
const handleSearch = () => {
  if (!searchKey.value.trim()) {
    filteredFactoryList.value = [...factoryList.value];
  } else {
    const keyword = searchKey.value.trim();
    filteredFactoryList.value = factoryList.value.filter(item => 
      item.brand.includes(keyword) ||
      item.agentBrand.includes(keyword) ||
      item.responsiblePerson.includes(keyword)
    );
  }
  total.value = filteredFactoryList.value.length;
  currentPage.value = 1; // 重置页码
};

// 返回按钮
const handleReturn = () => {
  // 实际项目中可通过路由返回上一页
  ElMessage.info('返回上一级页面');
};

// 新增采购
const handleAddPurchase = (row) => {
  purchaseForm.value.factory = row.brand;
  currentFactory.value = row;
  addPurchaseVisible.value = true;
};

// 保存采购
const handleSavePurchase = () => {
  if (!purchaseForm.value.product || !purchaseForm.value.amount) {
    ElMessage.error('请填写采购商品和金额');
    return;
  }
  // 模拟提交采购单
  ElMessage.success('采购单提交成功');
  addPurchaseVisible.value = false;
};

// 往期订单
const handleHistoryOrder = () => {
  // 模拟往期订单数据
  historyOrderList.value = [
    {
      orderNo: 'CG20240601001',
      product: '阿玛尼口红',
      count: 50,
      amount: '¥25000',
      createTime: '2024-06-01',
      status: '已完成'
    },
    {
      orderNo: 'CG20240515002',
      product: '阿玛尼粉底液',
      count: 30,
      amount: '¥18000',
      createTime: '2024-05-15',
      status: '已完成'
    }
  ];
  historyOrderVisible.value = true;
};

// 查看工厂详情
const handleView = (row) => {
  currentFactory.value = row;
  factoryDetailVisible.value = true;
};

// 素材库
const handleMaterialLibrary = () => {
  materialLibraryVisible.value = true;
};

// 预览素材
const handlePreview = (file) => {
  previewUrl.value = file.url;
  previewVisible.value = true;
};

// 分页切换
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 每页条数切换
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置页码
};

// 页码跳转
const handleJumpPage = () => {
  const page = Number(jumpPage.value);
  if (isNaN(page) || page < 1 || page > totalPages.value) {
    ElMessage.error(`请输入1-${totalPages.value}之间的页码`);
    return;
  }
  currentPage.value = page;
};
</script>

<style scoped>
.factory-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.return-btn {
  color: #666;
}

.search-area {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.search-btn {
  background-color: #10b981;
  border-color: #10b981;
}

.el-table {
  font-size: 13px;
}

.el-table th {
  background-color: #f5f7fa;
}

.pagination-area span {
  color: #666;
}

.upload-demo {
  margin-bottom: 20px;
}
</style>